import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: cz
 */
class BackupThread extends Thread {
    private final ServerSocket serverSocket;

    public BackupThread() throws IOException {
        serverSocket = new ServerSocket(RegionServer.FAILURE_PORT);
        serverSocket.setSoTimeout(Integer.MAX_VALUE);
    }

    @Override
    public void run() {
        while (true) {
            try {
                Socket server = serverSocket.accept();
                DataInputStream dataInputStream = new DataInputStream(server.getInputStream());

                String response = "Region Backup Fail!";
                String node = dataInputStream.readUTF();
                System.out.println(node + " need to be reconstruct!");
                if (FTPConnector.downloadAllFiles(node, "")) {
                    response = "Region BackUp Success!";
                    try {
                        API.initial();
                        ZookeeperManager.tableChange();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF(response);
                server.close();
            } catch (IOException s) {
                s.printStackTrace();
                break;
            }
        }
    }
}
